package com.liuqing.www.xml配置;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.commutils.DateUtils;
import com.game.common.AllConstants;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class FormInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation actions) throws Exception {
		
		Object action = actions.getAction() ;
//		System.out.println(action.getClass());
		autoSetFields(action ,actions.getInvocationContext()) ;
//		ActionContext context = actions.getInvocationContext() ;
//		
//		Object param = context.getParameters() ;
		
		
		return actions.invoke();
	}
	/**
	 * 通过反射，设置对象中所有的字段
	 * @param obj
	 */
	public static void autoSetFields(Object obj ,ActionContext context){
		Map<String,Object> param = AllConstants.formatParams(context.getParameters()) ;
		
		Class<?> clas = obj.getClass() ;
		
		for(Field field : clas.getDeclaredFields()){
			String name = field.getName() ;
//			System.out.println(name);
			if(param.containsKey(name)){
				
				String methodName = "set" + name.toUpperCase().charAt(0) + name.substring(1) ;
//				System.out.println(methodName);
				try {
					Method[] ms = clas.getDeclaredMethods() ;
					for(Method me : ms){
						if(me.getName().equals(methodName)){
//							System.out.println(me);
							Class[] ls = me.getParameterTypes() ;
							for(Class cl : ls){
//								System.out.println(cl);
								if(cl == long.class){
									Method setMethod = clas.getDeclaredMethod(methodName, new Class[]{long.class}) ;
									if(param.get(name) != null && !"".equals(param.get(name))){
										Object obpm = param.get(name) ;
										long ps = Long.parseLong(obpm.toString()) ;
										setMethod.invoke(obj, new Object[]{ps} ) ;
									}
								}else if(cl == int.class){
									Method setMethod = clas.getDeclaredMethod(methodName, new Class[]{int.class}) ;
									if(param.get(name) != null && !"".equals(param.get(name))){
										Object obpm = param.get(name) ;
										int ps = Integer.parseInt(obpm.toString()) ;
										setMethod.invoke(obj, new Object[]{ps} ) ;
									}
								}else{
									Method setMethod = clas.getDeclaredMethod(methodName, new Class[]{java.lang.String.class}) ;
									setMethod.invoke(obj, new Object[]{(String)param.get(name)} ) ;
								}
							}
						}
					}
//					Method setMethod = clas.getDeclaredMethod(methodName, new Class[]{java.lang.String.class}) ;
//					setMethod.invoke(obj, new Object[]{(String)param.get(name)} ) ;
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
			
		}
		
		
	}
	
	
}
